﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLBH.DataModel;
using System.Transactions;

namespace QLBH.Model.Controller
{
    public class KhoController : QLBHEntityBase<KHO>
    {
        public static KhoController GetInstance()
        {
            return new KhoController();
        } 
        public override KHO Add(KHO entity)
        {
            if (FindBy(it => it.KHOCODE == entity.KHOCODE).FirstOrDefault() != null)
            {
                throw new Exception("Mã kho đã tồn tại!");
            }
            if (FindBy(it => it.TENKHO == entity.TENKHO).FirstOrDefault() != null)
            {
                throw new Exception("Tên kho đã tồn tại!");
            } 
            if (entity.MACDINH==true)
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
                {
                    foreach (KHO k in Context.KHOes)
                    {
                        k.MACDINH = false;
                    }                    
                
                    base.Add(entity);
                    scope.Complete();
                }
                    return entity;
              
            }
            else
            {
                return base.Add(entity);
            }
            
        }
        public override KHO Edit(KHO entity)
        {
            if (FindBy(it => it.KHOCODE == entity.KHOCODE && it.KHOID!=entity.KHOID).FirstOrDefault() != null)
            {
                throw new Exception("Mã kho đã tồn tại!");
            }
            if (FindBy(it => it.TENKHO == entity.TENKHO && it.KHOID != entity.KHOID).FirstOrDefault() != null)
            {
                throw new Exception("Tên kho đã tồn tại!");
            } 
            if (entity.MACDINH == true)
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
                {
                    foreach (KHO k in GetAll().Where(kh => kh.KHOID!=entity.KHOID))
                    {
                        k.MACDINH = false;
                        Context.CreateObjectSet<KHO>().ApplyCurrentValues(k);
                    }
                    entity = base.Edit(entity);
                    scope.Complete();                    
                    return entity;
                }
            }
            else
            {
                return base.Edit(entity);
            }
        }
        public KHO GetKhoDefault()
        {
            return FindBy(kho => kho.MACDINH == true).FirstOrDefault();
        }
    }
}
